package com.fragrance.listener;

import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.model.Message;
import com.fragrance.service.IotRecvDataProcessService;
import com.fragrance.service.impl.IotRecvDataProcessServiceImpl;

/**
 * https://help.aliyun.com/document_detail/68948.html?spm=a2c4g.11174283.6.552.KTp0Ba
 * 
 * @author zhilin
 *
 */
public class IotMnsTaskListener implements Runnable {

	private Logger logger = LoggerFactory.getLogger(IotMnsTaskListener.class);

	private String AccessKeyId;

	private String AccessKeySecret;

	private String AccountEndpoint;

	private String queueName;
	
	private IotRecvDataProcessService iotRecvDataProcessService = new IotRecvDataProcessServiceImpl();
	
	//返回的数据包括
	private static final String DATA_CONTAINS = "AT+CLOUDSUB";

	public String getAccessKeyId() {
		return AccessKeyId;
	}

	public void setAccessKeyId(String accessKeyId) {
		AccessKeyId = accessKeyId;
	}

	public String getAccessKeySecret() {
		return AccessKeySecret;
	}

	public void setAccessKeySecret(String accessKeySecret) {
		AccessKeySecret = accessKeySecret;
	}

	public String getAccountEndpoint() {
		return AccountEndpoint;
	}

	public void setAccountEndpoint(String accountEndpoint) {
		AccountEndpoint = accountEndpoint;
	}

	public String getQueueName() {
		return queueName;
	}

	public void setQueueName(String queueName) {
		this.queueName = queueName;
	}

	public IotMnsTaskListener() {
	}

	public IotMnsTaskListener(String accessKeyId, String accessKeySecret, String accountEndpoint, String queueName) {
		super();
		this.AccessKeyId = accessKeyId;
		this.AccessKeySecret = accessKeySecret;
		this.AccountEndpoint = accountEndpoint;
		this.queueName = queueName;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void run() {
		if (StringUtils.isEmpty(AccessKeyId)) {
			logger.error("AccessKeyId不能为空，请在iotcfg.properties配置");
			return;
		}
		if (StringUtils.isEmpty(AccessKeySecret)) {
			logger.error("AccessKeySecret不能为空，请在iotcfg.properties配置");
			return;
		}

		if (StringUtils.isEmpty(AccountEndpoint)) {
			logger.error("AccountEndpoint不能为空，请在iotcfg.properties配置");
			return;
		}
		CloudAccount account = new CloudAccount(AccessKeyId, AccessKeySecret, AccountEndpoint);
		MNSClient client = account.getMNSClient();
		// 参数请输入IoT自动创建的队列名称，例如上面截图中的aliyun-iot-3AbL0062osF
		CloudQueue queue = client.getQueueRef("aliyun-iot-a1NcRC0sKf8");
		int count = 0;
		while (true) {
			String jsonStr = null;
			Message popMsg = null;
			try {
				// 获取消息 长轮询等待时间为10秒
				popMsg = queue.popMessage(5);
				if (popMsg != null) {
					jsonStr = popMsg.getMessageBodyAsString();
					if (StringUtils.isNotEmpty(jsonStr)) {
						Map map = JSON.parseObject(jsonStr, Map.class);
						String payload = (String) map.get("payload");
						if (StringUtils.isNotEmpty(payload)) {
							byte[] base64Byte = Base64.decodeBase64(payload);
							// 获取原始消息
							// logger.info("PopMessage Body: " +
							// popMsg.getMessageBodyAsRawString());
							// 上送的数据
							String data = new String(base64Byte);
							// 开始处理真正的消息
							if(StringUtils.isNotEmpty(data)){
								if(data.toUpperCase().contains(DATA_CONTAINS)){
									logger.info("process msg： " + data);
									iotRecvDataProcessService.dataProcess(data);
								}else{
									//TODO 其他类型数据
									logger.info("other msg： " + data);
								}
							}else{
								logger.info("数据为空不处理-2");
							}
						} else {
							logger.info("payload为空不处理jsonStr=" + jsonStr);
						}
					} else {
						logger.info("数据为空不处理-1");
					}
				} else {
					count = count++;
					if(count == 100){
						//循环100次打印一次日志
						logger.info("Wait Msg...");
						count = 0;
					}
				}
			} catch (Exception e) {
				logger.error("处理数据发生异常:" + jsonStr, e);
			} finally {
				if (popMsg != null) {
					try {
						// 从队列中删除消息
						queue.deleteMessage(popMsg.getReceiptHandle());
					} catch (Exception e) {
					}
				}
			}
		}
	}

}
